package com.cnpc.iot.mobile.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cnpc.framework.base.dao.RedisDao;
import com.cnpc.framework.base.entity.Org;
import com.cnpc.framework.base.entity.SysFile;
import com.cnpc.framework.base.entity.User;
import com.cnpc.framework.base.entity.UserAvatar;
import com.cnpc.framework.base.service.BaseService;
import com.cnpc.framework.base.service.UserService;
import com.cnpc.framework.utils.DateUtil;
import com.cnpc.framework.utils.EncryptUtil;
import com.cnpc.iot.mobile.controller.vo.BatchVo;
import com.cnpc.iot.mobile.controller.vo.CameraVo;
import com.cnpc.iot.mobile.controller.vo.DeviceVo;
import com.cnpc.iot.mobile.controller.vo.MorgVo;
import com.cnpc.iot.mobile.controller.vo.PflowVo;
import com.cnpc.iot.mobile.controller.vo.PnodeVo;
import com.cnpc.iot.mobile.controller.vo.ScglAdd;
import com.cnpc.iot.mobile.controller.vo.ScglDetail;
import com.cnpc.iot.mobile.controller.vo.ScglMobileVo;
import com.cnpc.iot.mobile.controller.vo.ScglVo;
import com.cnpc.iot.mobile.controller.vo.UserVo;
import com.cnpc.iot.mobile.service.MobileService;
import com.cnpc.iot.scene.entity.Device;
import com.cnpc.iot.scene.entity.Metrics;
import com.cnpc.iot.scene.entity.Sensor;
import com.cnpc.iot.scene.vo.SensorVo;
import com.cnpc.iot.scgl.controller.BatchController;
import com.cnpc.iot.scgl.entity.Batch;
import com.cnpc.iot.scgl.entity.Camera;
import com.cnpc.iot.scgl.entity.Pflow;
import com.cnpc.iot.scgl.entity.Pnode;
import com.cnpc.iot.scgl.utils.QrcodeUtils;

@Controller
@RequestMapping("/mobile")
public class MobileController {
	private String REDIS_COLL_KEY = "DEVICEDATA:";

	@Resource
	private BaseService baseService;

	@Resource
	private RedisDao redisDao;

	@Resource
	private MobileService mobileService;
	
	@Resource
    private UserService userService;

	@RequestMapping(value = "/getOrg/{level}", method = RequestMethod.GET)
	@ResponseBody
	public List<MorgVo> getBatchByPor(HttpServletRequest request, @PathVariable("level") String level) {
		List<Org> orgs = baseService.find("from Org where orgType='" + level + "'");
		List<MorgVo> mvos = new ArrayList<>();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath();
		for (Org i : orgs) {
			List<Org> subs = baseService.find("from Org where parentId='" + i.getId() + "'");
			MorgVo vo = new MorgVo();
			vo.setId(i.getId());
			vo.setName(i.getName());
			vo.setOrgLevel(i.getOrgType());
			vo.setRemark(i.getRemark());
			vo.setImages(basePath + i.getImages());
			if (null != subs && subs.size() > 0) {
				vo.setHaveSubs(true);
			} else {
				vo.setHaveSubs(false);
			}
			mvos.add(vo);
		}
		return mvos;
	}

	@RequestMapping(value = "/getOrgByParent/{parnet}", method = RequestMethod.GET)
	@ResponseBody
	public List<MorgVo> getOrgByParent(HttpServletRequest request, @PathVariable("parnet") String parnet) {
		List<Org> orgs = baseService.find("from Org where parentId='" + parnet + "'");
		List<MorgVo> mvos = new ArrayList<>();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath();
		for (Org i : orgs) {
			List<Org> subs = baseService.find("from Org where parentId='" + i.getId() + "'");
			MorgVo vo = new MorgVo();
			vo.setId(i.getId());
			vo.setName(i.getName());
			vo.setOrgLevel(i.getOrgType());
			vo.setRemark(i.getRemark());
			vo.setImages(basePath + i.getImages());
			if (null != subs && subs.size() > 0) {
				vo.setHaveSubs(true);
			} else {
				vo.setHaveSubs(false);
			}
			mvos.add(vo);
		}
		return mvos;
	}

	@RequestMapping(value = "/getDevice/{orgId}", method = RequestMethod.GET)
	@ResponseBody
	public List<DeviceVo> getDevice(@PathVariable("orgId") String orgId) {
		List<Device> orgs = baseService.find("from Device where orgid='" + orgId + "' and type='采集器'");
		List<DeviceVo> dvos = new ArrayList<>();
		if (null != orgs && orgs.size() > 0) {
			for (Device i : orgs) {
				DeviceVo vo = new DeviceVo();
				vo.setId(i.getId());
				vo.setType(i.getType());
				vo.setRemark(i.getRemark());
				dvos.add(vo);
			}
		}
		return dvos;
	}

	@RequestMapping(value = "/getSensor/{deviceId}", method = RequestMethod.GET)
	@ResponseBody
	public List<SensorVo> getSensor(@PathVariable("deviceId") String deviceId) {
		String hql = "from Sensor where deviceId=:deviceId";
		Map<String, Object> params = new HashMap<>();
		params.put("deviceId", deviceId);
		List<Sensor> sensors = baseService.find(hql, params);
		List<SensorVo> list = new ArrayList<>();
		if (null != sensors && sensors.size() > 0) {
			List<Metrics> metrics = redisDao.getList(REDIS_COLL_KEY + deviceId, Metrics.class);
			for (Sensor i : sensors) {
				SensorVo vo = new SensorVo();
				vo.setDeviceId(i.getDeviceId());
				vo.setIcon(i.getIcon());
				vo.setName(i.getType().getName());
				vo.setSensorId(i.getId());
				vo.setUnit(i.getUnit());
				vo.setValues("Na");
				if (null != metrics && metrics.size() > 0) {
					for (Metrics k : metrics) {
						if (i.getId().equals(k.getTags().get("scode"))) {
							vo.setValues(String.valueOf(k.getValue()));
						}
					}
				}
				list.add(vo);
			}
		}
		return list;
	}

	@RequestMapping(value = "/getCameras", method = RequestMethod.GET)
	@ResponseBody
	public List<CameraVo> getCameras() {
		List<Camera> cameras = baseService.find("from Camera");
		List<CameraVo> vos = new ArrayList<>();
		if (null != cameras && cameras.size() > 0) {
			for (Camera i : cameras) {
				CameraVo vo = new CameraVo();
				vo.setCameraAdd(i.getCameraAdd());
				vo.setCameraType(i.getCameraType());
				vo.setDeviceSerial(i.getDeviceSerial());
				vo.setHls(i.getHls());
				vo.setHlsHd(i.getHlsHd());
				vo.setId(i.getId());
				vo.setName(i.getName());
				vo.setRemark(i.getRemark());
				vo.setRtmp(i.getRtmp());
				vo.setRtmpHd(i.getRtmpHd());
				vo.setZiboUrl(i.getZiboUrl());
				vos.add(vo);
			}
		}
		return vos;
	}

	@RequestMapping(value = "/toVideoPlay/{cameraId}", method = RequestMethod.GET)
	public String toVideoPlay(@PathVariable("cameraId") String cameraId, HttpServletRequest request) {
		Camera camera = baseService.get(Camera.class, cameraId);
		request.setAttribute("camera", camera);
		return "mobile/videoPlay";
	}
	
	@RequestMapping(value = "/getPflow", method = RequestMethod.GET)
	@ResponseBody
	public List<PflowVo> getPflow() {
		List<Pflow> pflows = baseService.find("from Pflow");
		List<PflowVo> vos = new ArrayList<>();
		if (null != pflows && pflows.size() > 0) {
			for (Pflow i : pflows) {
				PflowVo vo = new PflowVo();
				vo.setId(i.getId());
				vo.setName(i.getName());
				vo.setCode(i.getCode());
				vo.setRemark(i.getRemark());
				vo.setActive(i.getActive());
				vos.add(vo);
			}
		}
		return vos;
	}

	@RequestMapping(value = "/getBatchByFlowId/{proId}", method = RequestMethod.GET)
	@ResponseBody
	public List<BatchVo> getBatchByFlowId(@PathVariable("proId") String proId) {
		List<Batch> batchs = baseService.find("from Batch where proName='" + proId + "'");
		List<BatchVo> vos = new ArrayList<>();
		if (null != batchs && batchs.size() > 0) {
			for (Batch i : batchs) {
				BatchVo vo = new BatchVo();
				vo.setId(i.getId());
				vo.setProId(i.getProId());
				vo.setPcCode(i.getPcCode());
				vo.setPcName(i.getPcName());
				vo.setPcNum(i.getPcNum());
				vo.setProName(i.getProName());
				vos.add(vo);
			}
		}
		return vos;
	}

	@RequestMapping(value = "/getPnodeByFlowId/{proId}", method = RequestMethod.GET)
	@ResponseBody
	public List<PnodeVo> getPnodeByFlowId(@PathVariable("proId") String proId) {
		List<Pnode> pnodes = baseService.find("from Pnode where flowId='" + proId + "'");
		List<PnodeVo> vos = new ArrayList<>();
		if (null != pnodes && pnodes.size() > 0) {
			for (Pnode i : pnodes) {
				PnodeVo vo = new PnodeVo();
				vo.setId(i.getId());
				vo.setName(i.getName());
				vo.setCode(i.getCode());
				vo.setFlowId(i.getFlowId());
				vo.setOrderId(i.getOrderId());
				vo.setCron(i.getCron());
				vos.add(vo);
			}
		}
		return vos;
	}

	@RequestMapping(value = "/getPnodeByBatchId/{batchId}", method = RequestMethod.GET)
	@ResponseBody
	public List<PnodeVo> getPnodeByBatchId(@PathVariable("batchId") String batchId) {
		List<PnodeVo> vos = new ArrayList<>();
		Batch batch = baseService.get(Batch.class, batchId);
		if (null != batch) {
			List<Pnode> pnodes = baseService.find("from Pnode where flowId='" + batch.getProName() + "'");
			if (null != pnodes && pnodes.size() > 0) {
				for (Pnode i : pnodes) {
					PnodeVo vo = new PnodeVo();
					vo.setId(i.getId());
					vo.setName(i.getName());
					vo.setCode(i.getCode());
					vo.setFlowId(i.getFlowId());
					vo.setOrderId(i.getOrderId());
					vo.setCron(i.getCron());
					vos.add(vo);
				}
			}
		}

		return vos;
	}

	@RequestMapping(value = "/getScglData/{nodeId}/{parent}", method = RequestMethod.GET)
	@ResponseBody
	public List<ScglVo> getScglData(HttpServletRequest request, @PathVariable("nodeId") String nodeId,
			@PathVariable("parent") String parent) {
		List<ScglVo> vos = new ArrayList<>();
		Pnode pnode = baseService.get(Pnode.class, nodeId);
		if (null != pnode) {
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath();
			String code = pnode.getCode();
			String sql = "select id, parent, creater, optime, fileids, operats from dny_" + code + " where parent='"
					+ parent + "'";
			List<Map<String, Object>> list = baseService.findMapBySql(sql);
			if (null != list && list.size() > 0) {
				for (Map<String, Object> i : list) {
					ScglVo vo = new ScglVo();
					String fileids = (String) i.get("fileids");
					if (null != fileids) {
						String[] images = fileids.split(",");
						if (null != images && images.length > 0) {
							SysFile sysFile = baseService.get(SysFile.class, images[0]);
							vo.setImages(basePath + sysFile.getFilePath());
						}
					}
					vo.setCreater(String.valueOf(i.get("creater")));
					vo.setId(String.valueOf(i.get("id")));
					vo.setParent(String.valueOf(i.get("parent")));
					vo.setOptime(DateUtil.format((Date) i.get("optime"), DateUtil.formatStr_yyyyMMddHHmmss));
					vo.setOperats(String.valueOf(i.get("operats")));
					vos.add(vo);
				}
			}
		}
		return vos;
	}
	
	
	@RequestMapping(value = "/getScglDetail/{nodeId}/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ScglDetail getScglDetail(HttpServletRequest request, @PathVariable("nodeId") String nodeId,
			@PathVariable("id") String id) {
		ScglDetail detail = new ScglDetail();
		Pnode pnode = baseService.get(Pnode.class, nodeId);
		if (null != pnode) {
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath();
			String code = pnode.getCode();
			String sql = "select id, parent, creater, optime, fileids, operats from dny_" + code + " where id='"
					+ id + "'";
			List<Map<String, Object>> list = baseService.findMapBySql(sql);
			if (null != list && list.size() == 1) {
				Map<String, Object> map = list.get(0);
				String fileids = (String) map.get("fileids");
				List<String> urls = new ArrayList<String>();
				if (null != fileids) {
					String[] images = fileids.split(",");
					if (null != images && images.length > 0) {
						for(String i : images) {
							SysFile sysFile = baseService.get(SysFile.class, i);
							urls.add(basePath + sysFile.getFilePath());
						}
					}
				}
				detail.setImgUrls(urls);
				detail.setId(String.valueOf(map.get("id")));
				detail.setOptime(DateUtil.format((Date) map.get("optime"), DateUtil.formatStr_yyyyMMddHHmmss));
				detail.setOperats(String.valueOf(map.get("operats")));
			}
		}
		return detail;
	}
	
	@RequestMapping(value = "/getScglDataByMobile/{nodeId}/{parent}", method = RequestMethod.GET)
	@ResponseBody
	public List<ScglMobileVo> getScglDataByMobile(HttpServletRequest request, @PathVariable("nodeId") String nodeId,
			@PathVariable("parent") String parent) {
		List<ScglMobileVo> vos = new ArrayList<>();
		Pnode pnode = baseService.get(Pnode.class, nodeId);
		if (null != pnode) {
//			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
//					+ request.getContextPath();
			String code = pnode.getCode();
			String sql = "select id, parent, creater, optime, fileids, operats from dny_" + code + " where parent='"
					+ parent + "' order by optime desc";
			List<Map<String, Object>> list = baseService.findMapBySql(sql);
			if (null != list && list.size() > 0) {
				for (Map<String, Object> i : list) {
					ScglMobileVo vo = new ScglMobileVo();
					String fileids = (String) i.get("fileids");
					if (null != fileids) {
						String[] images = fileids.split(",");
						if (null != images && images.length > 0) {
							List<String> imgs = new ArrayList<>();
							for(String k : images) {
								SysFile sysFile = baseService.get(SysFile.class, k);
								imgs.add(sysFile.getFilePath());
							}
							vo.setImages(imgs);
						}
					}
					vo.setCreater(String.valueOf(i.get("creater")));
					vo.setId(String.valueOf(i.get("id")));
					vo.setParent(String.valueOf(i.get("parent")));
					Date dt = (Date) i.get("optime");
					vo.setDate(DateUtil.format(dt, DateUtil.YYYY_MM_DD));
					vo.setTime(DateUtil.format(dt, DateUtil.HH_MM_SS));
					vo.setOperats(String.valueOf(i.get("operats")));
					vos.add(vo);
				}
			}
		}
		return vos;
	}
	

	@RequestMapping(value = "/addscgl", method = RequestMethod.POST)
	@ResponseBody
	public String addScglData(HttpServletRequest request, ScglAdd scglAdd) {
		System.out.println(scglAdd.getNodeId());
		String dirPath = request.getRealPath("/");
		mobileService.addScglData(dirPath, scglAdd);
		return "ok";
	}

	@RequestMapping(value = "/qrcode", method = RequestMethod.GET)
	@ResponseBody
	public String getPnodeByFlowId() {
		String qcode = QrcodeUtils.creatRrCode("http://www.baidu.com", 200, 200);
		return qcode;
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> login(String userName, String password) {
		String psw = EncryptUtil.getPassword(password, userName);
		List<User> users = baseService.find("from User where loginName='" + userName + "' and password='" + psw + "'");
		Map<String, String> resp = new HashMap<>();
		if(null != users && !users.isEmpty()) {
			User user = users.get(0);
			resp.put("code", "0");
			resp.put("userId", user.getId());
		}else {
			resp.put("code", "1");
		}
		return resp;
	}
	
	@RequestMapping(value = "/fwch/{fwm}", method = RequestMethod.GET)
    @ResponseBody
    private Object fwch(@PathVariable("fwm") String fwm) {
		List<String> nzm = redisDao.get(BatchController.NZM_REDIS_KEY, List.class);
		Map<String, Object> result = new HashMap<String,Object>();
		if(null != nzm) {
			if(nzm.contains(fwm)) {
				result.put("result", true);
				result.put("msg", "你所查询的产品真实有效");
			}else {
				result.put("result", false);
				result.put("msg", "未查询到产品信息");
			}
		}else {
			result.put("result", false);
			result.put("msg", "未查询到产品信息");
		}
		
		return result;
    }
	
	@RequestMapping(value = "/getUserAvatar/{userId}", method = RequestMethod.GET)
    @ResponseBody
    private UserAvatar getAvatar(@PathVariable("userId") String userId) {
		UserAvatar userAvatar = userService.getAvatarByUserId(userId);
		return userAvatar;
    }
	
	@RequestMapping(value="/main/{batchId}/{index}",method = RequestMethod.GET)
    public String toMobileMain(HttpServletRequest request, @PathVariable("batchId") String batchId, @PathVariable("index") String index){
		request.setAttribute("batchId", batchId);
		request.setAttribute("index", index);
        return "mobile/default";
    }
	
	@RequestMapping(value="/toPage/{page}/{batchId}",method = RequestMethod.GET)
    public String toMobilePage(HttpServletRequest request, @PathVariable("page") String page, @PathVariable("batchId") String batchId){
		request.setAttribute("batchId", batchId);
        return "mobile/" + page;
    }
	
}
